Skip to main content

Optionals

An optional value either contains a value of a given type or is absent. The absence of a value is represented by nil. The type of an optional is written as T?, where T is the underlying type.

Declaring Optionals

var name: String? = "Alice"
var age: Int? = nil

nil

nil represents the absence of a value and can be assigned to any optional:

var value: Float? = 3.14
value = nil

Checking for a Value

Compare an optional against nil to determine whether it holds a value:

var name: String? = "Alice"

if name != nil {
print("Name is present")
}

Unwrapping

Place an exclamation mark (!) after any expression that yields an optional to access its underlying value. This is called force unwrapping.

var phone_book = ["Alice": "01234", "Bob": "56789"]

fun find(_ name: String) -> (String?) {
return phone_book[name]
}

// Unwrapping a variable
var result = find("Alice")
print("\{result!}")

// Unwrapping directly on a function call
print("\{find("Alice")!}")
caution

Force unwrapping a nil optional causes a runtime error. Always verify the optional holds a value before unwrapping.

Optionals from Map Lookups

Accessing a map by key returns an optional, since the key may not exist:

var phone_book: [String: String] = ["Alice": "01234"]
var number = phone_book["Alice"] // type: String?

if number != nil {
print("Number: \{number!}")
}

Optionals in Ternary Expressions

A ternary expression can produce an optional result:

var condition: Bool = true
var result: String? = condition ? "value" : nil